package com.kehutong.user.app;

import com.kehutong.common.DoveClient;
import com.kehutong.common.util.AppDataPvUtils;
import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.Resident;
import com.kehutong.contact.entity.ResidentHouse;
import com.kehutong.contact.enums.BindType;
import com.kehutong.contact.enums.ResidentType;
import com.kehutong.contact.service.DataPvService;
import com.kehutong.contact.service.impl.ResidentServiceImpl;
import com.kehutong.user.entity.AssetsUserRemark;
import com.kehutong.user.service.AssetsUserService;
import com.kehutong.user.service.ShopUserService;
import org.coraframework.authz.HasPermission;
import org.coraframework.bean.Beans;
import org.coraframework.boot.Application;
import org.coraframework.config.Config;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.Objects;
import org.coraframework.util.UUIDGenerator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 企业微信用户控制器
 * 前端账号体系对应的住户
 * 用户
 * 住户
 * 业主
 * 租客
 * 家属
 * 商户
 * 业主
 * 车户
 * 业主
 *
 * @author: liukunlong
 * @date: 2021-08-04 11:45
 */
@MvcAction
@ReqMapping("/kht-bin/crm/assets/user")
public class AssetsUserAction {

    static final Logger logger = LoggerFactory.getLogger(AssetsUserAction.class);

    @Inject
    private ResidentServiceImpl residentService;


    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private DoveClient doveClient;

    @Inject
    private DataPvService dataPvService;

    @Inject
    private ShopUserService shopUserService;

    @Inject
    private AssetsUserService assetsUserService;


    /**
     * 新增或变更房屋业主信息
     *
     * @param resident 住户对象
     * @return 结果
     * @throws Exception 异常
     */
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/saveOrUpdateHouseOwner")
    public Object saveOrUpdateHouseOwner(Token token, Resident resident) throws Exception {
        resident.setCompanyNo(token.getCompanyNo());
        resident.setCompanyName(token.getCompanyName());
        resident.setCreateBy(token.getUuid());
        resident.setCreateName(token.getUsername());
        return residentService.saveOrUpdateHouseOwner(resident);
    }

    /**
     * 获取住户信息分页列表
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ReqMapping("/resident/page")
    public Object residentPage(JSONObject jsonObject) throws Exception {
        Page<Resident> page = residentService.getResidentList(jsonObject);
        return Result.success(page);
    }

    /**
     * 获取客户分页列表
     *
     * @param token
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ReqMapping("/customer/page")
    public Object customerPage(Token token, JSONObject jsonObject) throws Exception {
        jsonObject.remove("token");
        //查询有跟进人信息的用户信息
        //jsonObject.put("isExistUser", "1");
        //查询自己跟进的客户
        jsonObject.put("userIds",token.getUuid());
        Page<Resident> page = residentService.getResidentList(jsonObject);
        return Result.success(page);
    }

    /**
     * 获取企业微信住户分页列表
     * 绑定过任何资产的用户
     * @param token
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ReqMapping("/page")
    public Object page(Token token, JSONObject jsonObject) throws Exception {
        jsonObject.remove("token");
        //jsonObject.put("userIds", token.getUuid());

        //构建多个标志查询
        JSONArray ids = jsonObject.getJSONArray("ids");
        JSONArray tagIds = jsonObject.getJSONArray("tagIds");
        jsonObject.put("communityNos", AppDataPvUtils.getAppCommunityDataPv(token,jsonObject));
        Page<Map<String, Object>> page = assetsUserService.assetsUserPage(jsonObject);
        return Result.success(page);
    }


    /**
     * 获取用户信息
     *
     * @param token      用户信息
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/get")
    public Object get(Token token, JSONObject jsonObject) throws Exception {
        jsonObject.remove("token");
        //jsonObject.put("userIds", token.getUuid());
        jsonObject.put("id", jsonObject.getString("id"));
        Page<Resident> page = residentService.getResidentList(jsonObject);
        List<Resident> residentList = page.getList();
        if (Objects.isEmpty(residentList)) {
            return Result.success();
        }
        return Result.success(residentList.get(0));
    }


    /**
     * 更新用户信息
     *
     * @param token    登录信息
     * @param resident 住户对象
     * @return 结果对象
     * @throws Exception 异常
     */
    @Bean(copy = true)
    @ReqMapping("/update")
    public Object update(Token token, Resident resident) throws Exception {
        //设置当前住户跟进人信息
        //resident.setUserId(token.getUuid());
        resident.setCompanyNo(token.getCompanyNo());
        resident.setCompanyName(token.getCompanyName());
        resident.setCreateBy(token.getUuid());
        resident.setCreateName(token.getUsername());
        residentService.updateResident(resident);
        return Result.success();
    }


    /**
     * 用户信息统计
     *
     * @param token
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/count")
    public Object count(Token token, JSONObject jsonObject) throws Exception {
        JSONObject result = new JSONObject();
        jsonObject.remove("token");
        JSONObject workOrderCount = doveClient.post("/work/order/manage/service/app/count", (http) -> {
            http.setBody(jsonObject.toJSONString());
        });
        if (workOrderCount.getIntValue("code") == 200) {
            JSONObject data=workOrderCount.getJSONObject("data");
            result.put("complaintCount", data.getIntValue("complaintCount"));
            result.put("repairCount", data.getIntValue("repairCount"));
            result.put("appraisalCount", data.getIntValue("appraisalCount"));
        }
        return Result.success(result);
    }

    /**
     * 历史会话
     * euserId 可以为空
     * cuserId 不可为空
     * pageNo不可为空
     * pageSize不可为空
     *
     * @param token
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/history/session")
    public Object historySession(Token token, JSONObject jsonObject) throws Exception {
        jsonObject.remove("token");
        String euserId = jsonObject.getString("euserId");
        String cuserId = jsonObject.getString("cuserId");
        if (Objects.isEmpty(euserId) || Objects.isEmpty(cuserId)) {
             return Result.error(1, "缺少必填参数");
        }

        // 根据企业编号获取企业id
        JSONObject rs = doveClient.post("/kht-bin/wwout/corp/getCorpId", http -> {
            http.addParam("companyNo", token.getCompanyNo());
        });
        int code = rs.getIntValue("code");
        if (code != 200) {
            return Result.error(code, "企业编号有误");
        }

        Config config = Application.getConfig("web");
        String opinionUrl = config.getString("opinion_url");
        JSONObject result = doveClient.postExternal(opinionUrl + "/kht-bin/wework/chatinfo/list", (http) -> {
            http.addHeader("companyNo", rs.getString("data"));
            jsonObject.put("euserId", euserId);
            jsonObject.put("cuserId", cuserId);
            http.setBody(jsonObject.toJSONString());
        });
        JSONObject data = result.getJSONObject("data");
        if (data == null) {
            return Result.success(new Page<>());
        }
        return Result.success(data);
    }

    /**
     * 用户备注保存
     *
     * @param token
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/remark/save")
    public Object remarkSave(Token token, JSONObject jsonObject) throws Exception {

        //用户表那好
        String userNo = jsonObject.getString("userNo");
        //备注名称
        String name = jsonObject.getString("name");
        //描述
        String desc = jsonObject.getString("desc");
        //创建人
        String createBy = token.getUuid();


        FindOne<AssetsUserRemark> findOne = jdbcSession.findOne(AssetsUserRemark.class)
                .eq("userNo", userNo)
                .eq("createBy", createBy);
        AssetsUserRemark assetsUserRemark = findOne.exe();
        if (Objects.isNull(assetsUserRemark)) {
            assetsUserRemark = Pool.newInstance(AssetsUserRemark.class, UUIDGenerator.randomUUID());
            Beans.from(jsonObject).to(assetsUserRemark).exclude("id").igornNull().copy();
            assetsUserRemark.setCreateBy(createBy);
            assetsUserRemark.setCreateName(token.getUsername());
            jdbcSession.insert(assetsUserRemark);
        } else {
            JSONArray imageIds = jsonObject.getJSONArray("imageIds");
            List<String> list = new ArrayList<>();
            imageIds.forEach(images -> {
                list.add((String) images);
            });
            assetsUserRemark.setName(name);
            assetsUserRemark.setDesc(desc);
            assetsUserRemark.setImageIds(list);
            jdbcSession.updateById(assetsUserRemark);
        }
        return Result.success();
    }


    /**
     * 用户备注保存
     *
     * @param token
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/remark/get")
    public Object remarkGet(Token token, JSONObject jsonObject) throws Exception {
        //用户表那好
        String userNo = jsonObject.getString("userNo");

        //创建人
        String createBy = token.getUuid();


        FindOne<AssetsUserRemark> findOne = jdbcSession.findOne(AssetsUserRemark.class)
                .eq("userNo", userNo)
                .eq("createBy", createBy);
        AssetsUserRemark assetsUserRemark = findOne.exe();
        return Result.success(assetsUserRemark);
    }


    /***
     * 根据住户标志删除住户信息
     * @param id 住户标志
     * @return 操作结果
     * @throws Exception 操作异常
     */
    @ReqMapping("/delete")
    public Object deleteResidentById(String id) throws Exception {
        Resident resident = jdbcSession.findOne(Resident.class)
                .eq("id",id)
                .eq("deleted", false).exe();
        if(Objects.isNull(resident)){
            return Result.error(1,"当前住户已经删除.");
        }

        List<String> bindTypeList = new ArrayList<>();
        bindTypeList.add(BindType.BIND.getId());
        FindArray<ResidentHouse> findResidentHouse = jdbcSession.findArray(ResidentHouse.class)
                .eq("residentNo",id)
                .in("bindType", bindTypeList)
                .eq("deleted", false)
                .order("createTime", "desc");
        List<ResidentHouse> residentHouseList = findResidentHouse.exe();
        if(Objects.nonEmpty(residentHouseList)){
            return Result.error(1,"当前住户存在已绑定资产.");
        }

        //删除业主
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type",1);
        jsonObject.put("id",id);
        residentService.deleteResidentHouse(jsonObject);
        //删除家属及租客信息
        for(ResidentHouse residentHouse:residentHouseList){
            if(Objects.equal(ResidentType.FRIEND.getId(),residentHouse.getType().getId())){
                jsonObject.put("type",2);
                jsonObject.put("id",residentHouse.getId());
                residentService.deleteResidentHouse(jsonObject);
            }else if(Objects.equal(ResidentType.LESSEE.getId(),residentHouse.getType().getId())){
                jsonObject.put("type",3);
                jsonObject.put("id",residentHouse.getId());
                residentService.deleteResidentHouse(jsonObject);
            }
        }
        return Result.success();
    }


}
